<?php

namespace app\company\controller;

use app\company\validate\DeliverLineValidate;
use app\service\traits\Crud;
use app\company\model\DeliverLine as DeliverLineModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use think\Response;
use app\mini\model\Store;

class DeliverLine extends Base
{
    private DeliverLineModel $model;

    use Crud;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new DeliverLineModel();
        $this->validateClass = DeliverLineValidate::class;
        $this->isGs          = true;
        $this->withSearch    = 'id,no,name';
    }

    public function format($list)
    {
        return $list->each(function ($item) {
            $item->deliver_driver_name = $item->deliverDriver()
                                              ->value('name');//司机名
            $item->store_num           = $item->stores()
                                              ->count();      //门店数
        });
    }

    /**
     * 绑定门店
     * @param $store_id
     * @param $deliver_line_id
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function addStore($store_id, $deliver_line_id): Response
    {
        $storeModel = Store::where('id', $store_id)
                           ->where('deliver_line_id', 0)
                           ->find();
        if (!$storeModel) return $this->error('门店不存在或已被绑定');
        $storeModel->deliver_line_id = $deliver_line_id;
        $storeModel->save();
        DeliverLineModel::where('id', $deliver_line_id)
                        ->update(['update_time' => time()]);
        return $this->success('绑定成功');
    }


    /**
     * 解绑门店
     * @param $store_id
     * @param $deliver_line_id
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function delStore($store_id, $deliver_line_id): Response
    {
        $storeModel = Store::where('id', $store_id)
                           ->where('deliver_line_id', $deliver_line_id)
                           ->find();
        if (!$storeModel) return $this->error('门店不存在');
        $storeModel->deliver_line_id = 0;
        $storeModel->save();
        DeliverLineModel::where('id', $deliver_line_id)
                        ->update(['update_time' => time()]);
        return $this->success('删除成功');
    }


    public function detailFormat($info)
    {
        $info->deliver_driver_name = $info->deliverDriver()
                                          ->value('name');//司机名
        $info->warehouse           = $info->warehouse()
                                          ->field('id,name,long,lat')
                                          ->find();       //仓库
//        $info->stores              = $info->stores()->field('id,name,long,lat')->select();//门店s
        $info->stores = $this->getDistance($info);
        return $info;
    }

    // 坐标位置计算
    public function getDistance($info)
    {
        // 获取仓库坐标
        $wh_lat = $info->warehouse->lat;
        $wh_lng = $info->warehouse->long;
        if(!$wh_lng || !$wh_lng) exception('仓库坐标不存在,请配置仓库经纬度');
        // 计算距离的SQL表达式
        $distanceSql = "(6378.138 * 2 * ASIN(SQRT(
        POWER(SIN(({$wh_lat} - `lat`) * PI() / 180 / 2), 2) +
        COS({$wh_lat} * PI() / 180) * COS(`lat` * PI() / 180) *
        POWER(SIN(({$wh_lng} - `long`) * PI() / 180 / 2), 2))) * 1000) AS distance";

        // 查询该路线门店
        return Db::table('dt_store')
                 ->where('deliver_line_id', $info->id)
                 ->field("id,name,`long`,`lat`, {$distanceSql}")
                 ->bind([':wh_lat' => $wh_lat, ':wh_lng' => $wh_lng])
                 ->order('distance ASC')
                 ->select();
    }
}